package com.easybuilder.core.im.netty.websocket;

import com.easybuilder.common.utils.ThreadPoolUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class WebsocketServer implements InitializingBean {

    public static void main(String[] args) {
        start();
    }

    /** 启动netty服务 */
    public static void start() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 因为websocket基于http协议，所以使用http解码器
                            pipeline.addLast(new HttpServerCodec())
                                    // 可以分块对数据进行写入处理
                                    .addLast(new ChunkedWriteHandler())
                                    // http是分段传输，当数据量大时，会发起多次请求，HttpObjectAggregator可以将多次请求聚合(针对post请求，会把请求头与请求体聚合到一起)
                                    .addLast(new HttpObjectAggregator(8192))
                                    // websocket是以帧的形式进行数据传递，WebsocketFrame下有6个子类，当浏览器请求ws://localhost:6666/hello，表示请求的url
                                    // WebSocketServerProtocolHandler的核心功能：把http协议升级为websocket协议，保持长链接
                                    .addLast(new WebSocketServerProtocolHandler("/message"))
                                    .addLast(new WebsocketHandler());
                        }
                    });
            ChannelFuture future = bootstrap.bind(8088).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 此处使用多线程启动netty服务，防止在同一个线程中，netty服务启动后，阻塞spring启动流程
        ThreadPoolUtil.getExecutor().execute(() -> {
            start();
        });
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>> netty服务启动，端口:8088 >>>>>>>>>>>>>>>>>>>>>>>>>>>");
    }
}
